package com.task.manager.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class HttpClientUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	@Resource(name = "httpsClient")
	private HttpClient httpsClient;

	public String doGet(String url, Map<String, String> headers) {
		String result = "";
		try {
			HttpGet get = new HttpGet(url);
			if (!CollectionUtils.isEmpty(headers)) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					get.addHeader(entry.getKey(), entry.getValue());
				}
			}
			HttpResponse httpResponse = httpsClient.execute(get);
			HttpEntity resEntity = httpResponse.getEntity();
			result = EntityUtils.toString(resEntity);
		} catch (Exception e) {
			logger.error("HttpClientUtil_doGet_error:" + e.getMessage(), e);
		}

		return result;
	}

	public String doPost(String url, Map<String, String> param, HttpEntity entity, Map<String, String> headers) {
		String result = "";
		try {
			HttpPost post = new HttpPost(url);
			// 设置头信息
			if (!CollectionUtils.isEmpty(headers)) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}
			// 设置请求参数
			if (!CollectionUtils.isEmpty(param)) {
				List<NameValuePair> formparams = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> entry : param.entrySet()) {
					// 给参数赋值
					formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
				post.setEntity(urlEncodedFormEntity);
			}
			// 设置实体 优先级高
			if (entity != null) {
				post.setEntity(entity);
			}
			HttpResponse httpResponse = httpsClient.execute(post);
			HttpEntity resEntity = httpResponse.getEntity();
			result = EntityUtils.toString(resEntity);
		} catch (Exception e) {
			logger.error("HttpClientUtil_doPost_error:" + e.getMessage(), e);
		}

		return result;
	}
}
